<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Chart from 'chart.js/auto'
import { getHomeStatistics, getRealTimeRegisters, getHotDepartments, getHotDoctors, getDailyRegisters, getDailyRecharges } from '@/http/axiosRead'
import { User, Calendar, Setting, Money, UserFilled, Document } from '@element-plus/icons-vue'

// 响应式数据
const overviewList = ref([
  { label: '今日预约人数', value: 0, icon: 'Document', bg: 'linear-gradient(90deg,#3b82f6,#60a5fa)' },
  { label: '今日到诊人数', value: 0, icon: 'User', bg: 'linear-gradient(90deg,#f43f5e,#fbbf24)' },
  { label: '今日门诊收入', value: 0, icon: 'Money', bg: 'linear-gradient(90deg,#22c55e,#16a34a)' },
  { label: '今日充值金额', value: 0, icon: 'Setting', bg: 'linear-gradient(90deg,#f59e42,#fbbf24)' },
  { label: '新增患者人数', value: 0, icon: 'UserFilled', bg: 'linear-gradient(90deg,#a78bfa,#6366f1)' },
  { label: '今日挂号数', value: 0, icon: 'Calendar', bg: 'linear-gradient(90deg,#f472b6,#f87171)' },
])

const registerList = ref([])
const hotDeptList = ref([])
const hotDoctorList = ref([])



// 获取首页统计数据
const fetchHomeStatistics = async () => {
  try {
    const res = await getHomeStatistics()
    if (res.data.code === 200) {
      const data = res.data.data
      overviewList.value[0].value = data.todayAppointments || 0
      overviewList.value[1].value = data.todayVisits || 0
      overviewList.value[2].value = data.todayOutpatientRevenue || 0
      overviewList.value[3].value = data.todayRechargeAmount || 0
      overviewList.value[4].value = data.newPatients || 0
      overviewList.value[5].value = data.todayRegistrations || 0
    }
  } catch (error) {
    console.error('获取首页统计数据失败:', error)
  }
}

// 获取实时挂号数据
const fetchRealTimeRegisters = async () => {
  try {
    const res = await getRealTimeRegisters(10)
    if (res.data.code === 200) {
      registerList.value = res.data.data.map((item: any) => ({
        name: item.patientName,
        phone: item.phone,
        department: item.departmentName,
        doctor: item.doctorName,
        price: item.fee?.toFixed(2) || '0.00',
        time: new Date(item.registerTime).toLocaleString()
      }))
    }
  } catch (error) {
    console.error('获取实时挂号数据失败:', error)
  }
}

// 获取热门科室数据
const fetchHotDepartments = async () => {
  try {
    const res = await getHotDepartments(10)
    if (res.data.code === 200) {
      hotDeptList.value = res.data.data.map((item: any) => ({
        rank: item.rank,
        name: item.departmentName,
        count: item.appointmentCount
      }))
    }
  } catch (error) {
    console.error('获取热门科室数据失败:', error)
  }
}

// 获取热门医生数据
const fetchHotDoctors = async () => {
  try {
    const res = await getHotDoctors(10)
    if (res.data.code === 200) {
      hotDoctorList.value = res.data.data.map((item: any) => ({
        rank: item.rank,
        name: item.doctorName,
        count: item.appointmentCount
      }))
    }
  } catch (error) {
    console.error('获取热门医生数据失败:', error)
  }
}

// 初始化图表
const initCharts = async () => {
  try {
    // 获取每日挂号数据
    const registerRes = await getDailyRegisters()
    const registerData = registerRes.data.code === 200 ? registerRes.data.data : []

    // 获取每日充值数据
    const rechargeRes = await getDailyRecharges()
    const rechargeData = rechargeRes.data.code === 200 ? rechargeRes.data.data : []

    // 柱状图
    new Chart(document.getElementById('barChart') as HTMLCanvasElement, {
      type: 'bar',
      data: {
        labels: registerData.map((item: any) => item.date) || ['1月1日', '1月2日', '1月3日', '1月4日', '1月5日', '1月6日', '1月7日'],
        datasets: [{
          label: '挂号人数',
          data: registerData.map((item: any) => item.registerCount) || [3600, 5600, 7600, 5000, 7800, 5600, 6200],
          backgroundColor: '#3b82f6',
          borderRadius: 8,
        }]
      },
      options: {
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true } }
      }
    })

    // 折线图
    new Chart(document.getElementById('lineChart') as HTMLCanvasElement, {
      type: 'line',
      data: {
        labels: rechargeData.map((item: any) => item.date) || ['1月1日', '1月2日', '1月3日', '1月4日', '1月5日', '1月6日', '1月7日'],
        datasets: [{
          label: '充值金额',
          data: rechargeData.map((item: any) => item.rechargeAmount) || [20600, 59600, 78000, 21000, 59600, 30000, 11000],
          borderColor: '#f59e42',
          backgroundColor: 'rgba(245,158,66,0.1)',
          tension: 0.4,
          fill: true,
          pointRadius: 4,
          pointBackgroundColor: '#f59e42',
        }]
      },
      options: {
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true } }
      }
    })
  } catch (error) {
    console.error('初始化图表失败:', error)
  }
}



onMounted(async () => {
  // 并行获取所有数据
  await Promise.all([
    fetchHomeStatistics(),
    fetchRealTimeRegisters(),
    fetchHotDepartments(),
    fetchHotDoctors(),
    initCharts()
  ])
})
</script>

<template>
  <div class="home-root">
    <div class="page-header">
      <div class="page-title">Dashboard</div>
    </div>
    
    <!-- 统计卡片行 -->
    <div class="overview-row">
      <div class="overview-card" v-for="item in overviewList" :key="item.label" :style="{ background: item.bg }">
        <div class="overview-icon">
          <el-icon :size="32">
            <component :is="item.icon" />
          </el-icon>
        </div>
        <div class="overview-info">
          <div class="overview-value">{{ item.value }}</div>
          <div class="overview-label">{{ item.label }}</div>
        </div>
      </div>
    </div>
    
    <!-- 图表行 -->
    <div class="chart-row">
      <div class="chart-card">
        <div class="chart-title">近7日挂号预约情况</div>
        <div class="chart-content">
          <canvas id="barChart"></canvas>
        </div>
      </div>
      <div class="chart-card">
        <div class="chart-title">近7日门诊充值趋势</div>
        <div class="chart-content">
          <canvas id="lineChart"></canvas>
        </div>
      </div>
    </div>
    
    <!-- 数据表格行 -->
    <div class="table-row">
      <div class="table-card">
        <div class="table-title">实时挂号</div>
        <el-table :data="registerList" border style="width: 100%">
          <el-table-column prop="name" label="患者姓名" width="100" />
          <el-table-column prop="phone" label="手机号" width="140" />
          <el-table-column prop="department" label="科室" width="100" />
          <el-table-column prop="doctor" label="医生" width="100" />
          <el-table-column prop="price" label="挂号费" width="80" />
          <el-table-column prop="time" label="挂号时间" />
        </el-table>
      </div>
      <div class="table-card">
        <div class="table-title">热门科室</div>
        <el-table :data="hotDeptList" border style="width: 100%">
          <el-table-column prop="rank" label="排名" width="60" />
          <el-table-column prop="name" label="科室名称" />
          <el-table-column prop="count" label="预约人数" />
        </el-table>
      </div>
      <div class="table-card">
        <div class="table-title">热门医生</div>
        <el-table :data="hotDoctorList" border style="width: 100%">
          <el-table-column prop="rank" label="排名" width="60" />
          <el-table-column prop="name" label="医生姓名" />
          <el-table-column prop="count" label="预约人数" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 引入Kanit字体 */
@import url('https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600&display=swap');

.home-root {
  min-height: 100vh;
  background: linear-gradient(135deg, #D8D2FC 0%, #FDE2E0 28.35%, #E6E4EA 58.79%, #E0E9F4 100%);
  font-family: 'Kanit', 'Microsoft YaHei', sans-serif;
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 8px;
  border-bottom: 2px solid rgba(255, 255, 255, 0.3);
}

.page-title {
  font-size: 42px;
  font-weight: 500;
  color: #271E4A;
  margin: 0;
}

.overview-row {
  display: flex;
  gap: 18px;
  margin-bottom: 24px;
}

.overview-card {
  flex: 1;
  display: flex;
  align-items: center;
  border-radius: 20px;
  box-shadow: 0 4px 15px rgba(216, 210, 252, 0.64);
  padding: 18px 24px;
  color: #fff;
  min-width: 0;
}

.overview-icon {
  margin-right: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.12);
  border-radius: 12px;
}

.overview-value {
  font-size: 1.6rem;
  font-weight: bold;
}

.overview-label {
  font-size: 0.95rem;
  opacity: 0.9;
}

.chart-row {
  display: flex;
  gap: 18px;
  margin-bottom: 24px;
}

.chart-card {
  flex: 1;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 15px rgba(216, 210, 252, 0.64);
  padding: 18px 18px 8px 18px;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.chart-title {
  font-size: 1.1rem;
  font-weight: 500;
  color: #271E4A;
  margin-bottom: 8px;
}

.chart-content {
  flex: 1;
  min-height: 220px;
}

.table-row {
  display: flex;
  gap: 18px;
  margin-top: 8px;
}

.table-card {
  flex: 1;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 15px rgba(216, 210, 252, 0.64);
  padding: 18px 12px 12px 12px;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.table-title {
  font-size: 1.05rem;
  font-weight: 500;
  color: #271E4A;
  margin-bottom: 8px;
}

:deep(.el-table) {
  font-size: 14px;
  border-radius: 8px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .overview-row,
  .chart-row,
  .table-row {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
